package com.kuizii.demo.core.mq;


import com.alibaba.fastjson.JSON;
import com.kuizii.demo.domain.SendMailRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;


/**
 * 利用Redis消息队列发送邮件
 */

public class SendMessageListener implements MessageListener {


    @Autowired
    private JavaMailSenderImpl mailSender;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
        String msg = serializer.deserialize(message.getBody());
        System.out.println("接收到的消息是：" + msg);

        SendMailRequest request = JSON.parseObject(msg, SendMailRequest.class);
        //邮件
        SimpleMailMessage mimeMessage = new SimpleMailMessage();

        mimeMessage.setFrom("notify@kuizii.com");
        mimeMessage.setTo(request.getReciveEmail());
        mimeMessage.setSubject(request.getSubject());
        mimeMessage.setText(request.getContent());

        mailSender.send(mimeMessage);
    }
}
